using UnityEngine;
using System.Collections;

public class PowerUpController : MonoBehaviour
{
    [Header("道具基础设置")]
    public PowerUpType powerUpType = PowerUpType.SpreadShot;
    public float effectDuration = 10f;
    public float effectStrength = 1.5f;
    public int scoreValue = 50;
    [Tooltip("玩家碰到时是否应用效果（用于仅展示用掉落）")]
    public bool applyOnCollect = true;
    
    [Header("移动设置")]
    public float moveSpeed = 2f;
    public MovementPattern movementPattern = MovementPattern.StraightDown;
    public float amplitude = 1f;
    public float frequency = 2f;
    
    [Header("视觉效果")]
    public Color powerUpColor = Color.yellow;
    public bool hasGlow = true;
    public bool rotates = true;
    public float rotationSpeed = 90f;
    
    [Header("音效设置")]
    public bool playCollectSound = true;
    
    [Header("调试设置")]
    public bool showDebugInfo = false;
    
    private Vector3 startPosition;
    private float timeAlive;
    private SpriteRenderer spriteRenderer;
    private bool isCollected = false;
    
    public enum PowerUpType
    {
        SpreadShot,         // 散射弹幕
        BurstFire,          // 连发模式
        UpgradedBullet,     // 子弹升级（提升子弹等级，使用 UpgradedBullet 预制体）
        BulletUpgradePowerUp, // 子弹加强
        Clone               // 分身
    }
    
    public enum MovementPattern
    {
        StraightDown,
        SineWave,
        Float,
        Spiral
    }
    
    void Start()
    {
        startPosition = transform.position;
        
        SetupVisualComponents();
        SetupPhysics();
        ConfigurePowerUpAppearance();
        
        // 设置标签
        gameObject.tag = "PowerUp";
        
        Debug.Log($"道具已生成: 类型={powerUpType}, 效果强度={effectStrength}, 持续时间={effectDuration}s");
    }
    
    void Update()
    {
        if (isCollected) return;
        
        timeAlive += Time.deltaTime;
        
        HandleMovement();
        HandleRotation();
        CheckBoundaries();
        
        if (showDebugInfo)
        {
            Debug.Log($"道具状态: 类型={powerUpType}, 位置={transform.position}, 存活时间={timeAlive:F1}s");
        }
    }
    
    void SetupVisualComponents()
    {
        spriteRenderer = GetComponent<SpriteRenderer>();
        if (spriteRenderer == null)
        {
            spriteRenderer = gameObject.AddComponent<SpriteRenderer>();
        }
        
        // 创建道具精灵
        spriteRenderer.sprite = CreatePowerUpSprite();
        spriteRenderer.color = powerUpColor;
        
        // 添加发光效果
        if (hasGlow)
        {
            AddGlowEffect();
        }
    }
    
    void SetupPhysics()
    {
        // 添加碰撞器
        CircleCollider2D collider = GetComponent<CircleCollider2D>();
        if (collider == null)
        {
            collider = gameObject.AddComponent<CircleCollider2D>();
        }
        collider.radius = 0.4f;
        collider.isTrigger = true;
        
        // 添加刚体
        Rigidbody2D rb = GetComponent<Rigidbody2D>();
        if (rb == null)
        {
            rb = gameObject.AddComponent<Rigidbody2D>();
        }
        rb.gravityScale = 0f;
        rb.freezeRotation = !rotates;
    }
    
    void ConfigurePowerUpAppearance()
    {
        // 根据道具类型设置外观
        switch (powerUpType)
        {
            case PowerUpType.SpreadShot:
                powerUpColor = Color.blue;
                break;
            case PowerUpType.BurstFire:
                powerUpColor = new Color(1f, 0.5f, 0f); // 橙色
                break;
            case PowerUpType.UpgradedBullet:
                powerUpColor = Color.green; // 绿色表示升级
                break;
            case PowerUpType.BulletUpgradePowerUp:
                powerUpColor = new Color(0.8f, 0f, 0.8f); // 紫色，表示“子弹加强”
                break;
            case PowerUpType.Clone:
                powerUpColor = Color.cyan; // 青色，表示“分身”
                break;
        }
        
        if (spriteRenderer != null)
        {
            spriteRenderer.color = powerUpColor;
        }
    }
    
    void HandleMovement()
    {
        Vector3 movement = Vector3.zero;
        
        switch (movementPattern)
        {
            case MovementPattern.StraightDown:
                movement = Vector3.down * moveSpeed * Time.deltaTime;
                break;
                
            case MovementPattern.SineWave:
                float sineOffset = Mathf.Sin(timeAlive * frequency) * amplitude;
                Vector3 targetPos = startPosition + Vector3.right * sineOffset + Vector3.down * timeAlive * moveSpeed;
                transform.position = Vector3.MoveTowards(transform.position, targetPos, moveSpeed * Time.deltaTime);
                return;
                
            case MovementPattern.Float:
                float floatY = Mathf.Sin(timeAlive * frequency) * amplitude * 0.5f;
                float floatX = Mathf.Cos(timeAlive * frequency * 0.7f) * amplitude * 0.3f;
                movement = new Vector3(floatX, floatY - moveSpeed, 0) * Time.deltaTime;
                break;
                
            case MovementPattern.Spiral:
                float spiralAngle = timeAlive * frequency;
                float spiralRadius = amplitude * (1f - timeAlive * 0.1f);
                Vector3 spiralOffset = new Vector3(Mathf.Cos(spiralAngle), Mathf.Sin(spiralAngle), 0) * spiralRadius;
                Vector3 spiralTarget = startPosition + spiralOffset + Vector3.down * timeAlive * moveSpeed;
                transform.position = Vector3.MoveTowards(transform.position, spiralTarget, moveSpeed * Time.deltaTime);
                return;
        }
        
        transform.position += movement;
    }
    
    void HandleRotation()
    {
        if (rotates)
        {
            transform.Rotate(0, 0, rotationSpeed * Time.deltaTime);
        }
    }
    
    void CheckBoundaries()
    {
        if (BoundaryManager.Instance != null && BoundaryManager.Instance.IsOutOfBounds(transform.position))
        {
            DestroyPowerUp();
        }
    }
    
    void AddGlowEffect()
    {
        // 创建发光效果（简单版本）
        GameObject glowObj = new GameObject("Glow");
        glowObj.transform.SetParent(transform);
        glowObj.transform.localPosition = Vector3.zero;
        glowObj.transform.localScale = Vector3.one * 1.5f;
        
        SpriteRenderer glowRenderer = glowObj.AddComponent<SpriteRenderer>();
        glowRenderer.sprite = spriteRenderer.sprite;
        glowRenderer.color = new Color(powerUpColor.r, powerUpColor.g, powerUpColor.b, 0.3f);
        glowRenderer.sortingOrder = spriteRenderer.sortingOrder - 1;
        
        // 添加脉冲动画
        StartCoroutine(PulseGlow(glowObj));
    }
    
    IEnumerator PulseGlow(GameObject glowObj)
    {
        float pulseSpeed = 2f;
        Vector3 originalScale = glowObj.transform.localScale;
        
        while (glowObj != null && !isCollected)
        {
            float pulse = 1f + Mathf.Sin(Time.time * pulseSpeed) * 0.2f;
            glowObj.transform.localScale = originalScale * pulse;
            yield return null;
        }
    }
    
    void OnTriggerEnter2D(Collider2D other)
    {
        if (isCollected) return;
        
        if (other.CompareTag("Player"))
        {
            CollectPowerUp(other.gameObject);
        }
    }
    
    void CollectPowerUp(GameObject player)
    {
        isCollected = true;
        
        // 应用道具效果（可配置）
        if (applyOnCollect)
        {
            ApplyPowerUpEffect(player);
        }
        
        // 播放收集音效
        if (playCollectSound)
        {
            PlayCollectSound();
        }
        
        // 创建收集特效
        CreateCollectEffect();
        
        Debug.Log($"道具已收集: {powerUpType}, 玩家获得效果");
        
        // 销毁道具
        DestroyPowerUp();
    }
    
    void ApplyPowerUpEffect(GameObject player)
    {
        PowerUpManager powerUpManager = player.GetComponent<PowerUpManager>();
        if (powerUpManager == null)
        {
            powerUpManager = player.AddComponent<PowerUpManager>();
        }
        
        powerUpManager.ApplyPowerUp(powerUpType, effectDuration, effectStrength);
    }
    
    void PlayCollectSound()
    {
        // 简单的音效播放（可以后续扩展）
        Debug.Log($"播放收集音效: {powerUpType}");
    }
    
    void CreateCollectEffect()
    {
        GameObject effect = new GameObject("PowerUpCollectEffect");
        effect.transform.position = transform.position;
        
        ParticleSystem particles = effect.AddComponent<ParticleSystem>();
        var main = particles.main;
        main.startLifetime = 1f;
        main.startSpeed = 5f;
        main.startSize = 0.1f;
        main.startColor = powerUpColor;
        main.maxParticles = 15;
        
        var emission = particles.emission;
        emission.rateOverTime = 0;
        emission.SetBursts(new ParticleSystem.Burst[]
        {
            new ParticleSystem.Burst(0.0f, 15)
        });
        
        var shape = particles.shape;
        shape.shapeType = ParticleSystemShapeType.Circle;
        shape.radius = 0.3f;
        
        Destroy(effect, 2f);
    }
    
    Sprite CreatePowerUpSprite()
    {
        Texture2D texture = new Texture2D(32, 32);
        Color[] pixels = new Color[32 * 32];
        
        for (int i = 0; i < pixels.Length; i++)
        {
            int x = i % 32;
            int y = i / 32;
            
            // 创建星形道具图案
            Vector2 center = new Vector2(16, 16);
            Vector2 pos = new Vector2(x, y);
            float distance = Vector2.Distance(pos, center);
            float angle = Mathf.Atan2(y - 16, x - 16) * Mathf.Rad2Deg;
            
            // 星形图案
            float starRadius = 12f + Mathf.Sin(angle * Mathf.Deg2Rad * 5f) * 4f;
            
            if (distance <= starRadius && distance >= starRadius - 4f)
            {
                pixels[i] = Color.white;
            }
            else if (distance <= starRadius - 4f)
            {
                pixels[i] = new Color(1f, 1f, 1f, 0.7f);
            }
            else
            {
                pixels[i] = Color.clear;
            }
        }
        
        texture.SetPixels(pixels);
        texture.Apply();
        
        return Sprite.Create(texture, new Rect(0, 0, 32, 32), new Vector2(0.5f, 0.5f));
    }
    
    public void SetPowerUpType(PowerUpType type)
    {
        powerUpType = type;
        ConfigurePowerUpAppearance();
        Debug.Log($"道具类型已设置: {powerUpType}");
    }
    
    void DestroyPowerUp()
    {
        Debug.Log($"道具已销毁: {powerUpType}");
        Destroy(gameObject);
    }
    
    void OnDrawGizmos()
    {
        if (showDebugInfo)
        {
            // 绘制收集范围
            Gizmos.color = powerUpColor;
            Gizmos.DrawWireSphere(transform.position, 0.4f);
            
            // 绘制移动路径预览
            if (movementPattern == MovementPattern.SineWave)
            {
                Gizmos.color = Color.yellow;
                for (float t = 0; t < 3f; t += 0.1f)
                {
                    float sineOffset = Mathf.Sin(t * frequency) * amplitude;
                    Vector3 pos = startPosition + Vector3.right * sineOffset + Vector3.down * t * moveSpeed;
                    Gizmos.DrawWireSphere(pos, 0.1f);
                }
            }
        }
    }
}